import React, { useEffect, useState } from 'react';
import '../components.css';
import FundsrecoverymanagementService from '../../services/FundsrecoverymanagementService';
import {
  DeleteOutlined, UpCircleOutlined, ImportOutlined,
  ExportOutlined, SortAscendingOutlined, ArrowUpOutlined,
  ArrowDownOutlined, AppstoreOutlined, TableOutlined,
  PlusOutlined, SearchOutlined, ReloadOutlined,
  EyeOutlined, CheckCircleOutlined, ClockCircleOutlined,
  CloseCircleOutlined, UndoOutlined,UploadOutlined
} from '@ant-design/icons';
import {
  Table, Button, Popconfirm, Space, message,
  Input, Select, DatePicker, Tag, Card, Form,
  Modal, Upload, Dropdown, Menu, List, Avatar,
  Tabs, Divider, Tooltip,Checkbox
} from 'antd';
import { Link, useNavigate } from 'react-router-dom';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

export default function FundsrecoverymanagementList() {

  // 添加新状态
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectAll, setSelectAll] = useState(false);
  // 状态管理
  const [fundrecoverymanagements, setFundrecoverymanagements] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [importLoading, setImportLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'ascend' });
  const [viewMode, setViewMode] = useState('table');

  const navigate = useNavigate();
  // 全选/反选处理函数
    const handleSelectAll = () => {
      if (selectAll) {
        setSelectedRowKeys([]);
      } else {
        const currentPageKeys = filteredData
          .slice((pagination.current - 1) * pagination.pageSize, pagination.current * pagination.pageSize)
          .map(item => item.id);
        setSelectedRowKeys(currentPageKeys);
      }
      setSelectAll(!selectAll);
    };

    // 反选当前页
    const handleInvertSelection = () => {
      const currentPageKeys = filteredData
        .slice((pagination.current - 1) * pagination.pageSize, pagination.current * pagination.pageSize)
        .map(item => item.id);

      const newSelectedKeys = currentPageKeys.filter(key => !selectedRowKeys.includes(key));
      setSelectedRowKeys(newSelectedKeys);
      setSelectAll(false);
    };

    // 单个选择处理函数
    const onSelectChange = (id) => {
      if (selectedRowKeys.includes(id)) {
        setSelectedRowKeys(selectedRowKeys.filter(key => key !== id));
        setSelectAll(false);
      } else {
        setSelectedRowKeys([...selectedRowKeys, id]);
      }
    };
  // 获取所有回款数据
  const getAllFundsrecoverymanagements = async (params = {}) => {
    setLoading(true);
    try {
      const response = await FundsrecoverymanagementService.getAllFundsrecoverymanagements(params);
      const data = response.data.map(item => ({
        ...item,
        key: item.id,
      }));
      setFundrecoverymanagements(data);
      setFilteredData(data);
      setPagination({
        ...pagination,
        total: data.length,
      });
      // 清除选中状态
      setSelectedRowKeys([]);
      setSelectAll(false);
    } catch (error) {
      message.error('加载回款数据失败');
      console.error('获取回款数据错误:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getAllFundsrecoverymanagements();
  }, []);

  // 标签页切换处理
  const handleTabChange = (key) => {
    setActiveTab(key);
    filterDataByTab(key, form.getFieldsValue());
  };

  // 根据标签页筛选数据
  const filterDataByTab = (tabKey, formValues) => {
    let filteredData = [...fundrecoverymanagements];

    // 标签页筛选
    if (tabKey === 'mine') {
      filteredData = fundrecoverymanagements.filter(item => item.responsiblePerson === '当前用户');
    } else if (tabKey === 'next') {
      filteredData = fundrecoverymanagements.filter(item => item.responsiblePerson !== '当前用户');
    }

    // 表单筛选条件
    filteredData = applyFormFilters(filteredData, formValues);

    setFilteredData(filteredData);
    setPagination(prev => ({
      ...prev,
      total: filteredData.length,
      current: 1,
    }));
  };

  // 应用表单筛选条件
  const applyFormFilters = (data, values) => {
    let result = [...data];

    // 关键词搜索
    if (values?.keyword) {
      const keyword = values.keyword.toLowerCase();
      result = result.filter(item =>
        (item.systemNumber && item.systemNumber.toLowerCase().includes(keyword)) ||
        (item.relatedOrder && item.relatedOrder.toLowerCase().includes(keyword))
      );
    }

    // 审批状态筛选
    if (values?.approvalstatus && values.approvalstatus !== 'all') {
      result = result.filter(item =>
        item.approvalStatus === values.approvalstatus
      );
    }

    // 逾期状态筛选
    if (values?.overduestatus && values.overduestatus !== 'all') {
      result = result.filter(item =>
        item.overdueStatus === values.overduestatus
      );
    }

    // 付款方式筛选
    if (values?.paymentmethod && values.paymentmethod !== 'all') {
      result = result.filter(item =>
        item.paymentMethod === values.paymentmethod
      );
    }

    // 日期范围筛选
    if (values?.dateRange && values.dateRange.length === 2) {
      const [start, end] = values.dateRange;
      result = result.filter(item => {
        const itemDate = item.countryDate ? new Date(item.countryDate) : null;
        if (!itemDate) return false;
        return itemDate >= start.startOf('day') && itemDate <= end.endOf('day');
      });
    }

    return result;
  };

  // 搜索处理
  const handleSearch = (values) => {
    filterDataByTab(activeTab, values);
  };

  // 重置搜索表单
  const onReset = () => {
    form.resetFields();
    filterDataByTab(activeTab, {});
  };

  // 删除回款
  const deleteFundsrecoverymanagement = (id) => {
    message.success('删除成功!');
    setTimeout(() => {
      FundsrecoverymanagementService.deleteFundsrecoverymanagement(id)
        .then(() => {
          getAllFundsrecoverymanagements();
        })
        .catch((error) => {
          console.log(error);
          message.error('删除失败!');
        });
    }, 500);
  };

  // 批量删除处理函数
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条记录');
      return;
    }

    Modal.confirm({
      title: '确定要批量删除选中的回款记录吗?',
      content: `您选择了 ${selectedRowKeys.length} 条记录，删除后将无法恢复。`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        FundsrecoverymanagementService.deleteFundsrecoverymanagement(selectedRowKeys)
          .then(() => {
            message.success(`成功删除 ${selectedRowKeys.length} 条回款记录`);
            getAllFundsrecoverymanagements();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            message.error('批量删除失败');
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  // 排序函数
  const requestSort = (key) => {
    let direction = 'ascend';
    if (sortConfig.key === key && sortConfig.direction === 'ascend') {
      direction = 'descend';
    }
    setSortConfig({ key, direction });

    // 执行排序
    const sortedData = [...filteredData].sort((a, b) => {
      // 处理可能为null或undefined的值
      const valueA = a[key] || '';
      const valueB = b[key] || '';

      if (valueA < valueB) {
        return direction === 'ascend' ? -1 : 1;
      }
      if (valueA > valueB) {
        return direction === 'ascend' ? 1 : -1;
      }
      return 0;
    });

    setFilteredData(sortedData);
  };

  // 获取排序图标
  const getSortIcon = (key) => {
    if (sortConfig.key !== key) {
      return <SortAscendingOutlined />;
    }
    return sortConfig.direction === 'ascend' ? <ArrowUpOutlined /> : <ArrowDownOutlined />;
  };

  // 显示导入弹窗
  const showImportModal = () => {
    setImportModalVisible(true);
  };

  // 隐藏导入弹窗
  const hideImportModal = () => {
    setImportModalVisible(false);
    setFileList([]);
  };

  // 处理文件上传变化
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 执行导入操作
  const handleImport = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择文件');
      return;
    }

    try {
      setImportLoading(true);
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files', file.originFileObj);
      });
      const response = await FundsrecoverymanagementService.importFundsrecoverymanagements(formData);

      if (response.status === 200) {
        message.success('导入成功！');
        getAllFundsrecoverymanagements();
        hideImportModal();
      } else {
        throw new Error(response.data?.message || '导入失败');
      }
    } catch (error) {
      console.error('导入失败:', error);
      message.error(error.response?.data?.message || '导入失败，请重试！');
    } finally {
      setImportLoading(false);
    }
  };

  // 导出功能
  const handleExport = async () => {
    try {
      setExportLoading(true);

      // 获取当前筛选条件
      const filterValues = form.getFieldsValue();
      const tabFilter = activeTab;

      // 调用导出API
      const response = await FundsrecoverymanagementService.exportFundsrecoverymanagements({
        ...filterValues,
        tabFilter
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;

      // 从Content-Disposition中获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let fileName = '回款数据.xlsx';
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename=(.+)/);
        if (fileNameMatch && fileNameMatch.length === 2) {
          fileName = fileNameMatch[1];
        }
      }
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();

      message.success('导出成功！');
    } catch (error) {
      console.error('导出失败:', error);
      message.error(error.response?.data?.message || '导出失败，请重试！');
    } finally {
      setExportLoading(false);
    }
  };

  // 排序菜单
  const sortMenu = (
    <Menu>
      <Menu.Item key="amountAsc" onClick={() => requestSort('paymentAmount')}>
        按金额升序
      </Menu.Item>
      <Menu.Item key="amountDesc" onClick={() => requestSort('paymentAmount', 'descend')}>
        按金额降序
      </Menu.Item>
      <Menu.Item key="dateAsc" onClick={() => requestSort('countryDate')}>
        按日期升序
      </Menu.Item>
      <Menu.Item key="dateDesc" onClick={() => requestSort('countryDate', 'descend')}>
        按日期降序
      </Menu.Item>
    </Menu>
  );

  // 卡片视图渲染
  const renderCardView = () => {
    return (
      <List
        grid={{ gutter: 16, column: 3 }}
        dataSource={filteredData}
        loading={loading}
        renderItem={(item) => (
          <List.Item>
            <Card
              title={`系统编号: ${item.systemNumber || '-'}`}
              actions={[
                <Tooltip title="详情" key="detail">
                  <Link to={`fundDetails/${item.id}`}>
                    <Button type="text" icon={<EyeOutlined />} />
                  </Link>
                </Tooltip>,
                <Tooltip title="更新" key="edit">
                  <Link to={`updatefunds/${item.id}`}>
                    <Button type="text" icon={<UpCircleOutlined />} />
                  </Link>
                </Tooltip>,
                <Tooltip title="删除" key="delete">
                  <Popconfirm
                    title="确定要删除此回款记录吗?"
                    onConfirm={() => deleteFundsrecoverymanagement(item.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="text" danger icon={<DeleteOutlined />} />
                  </Popconfirm>
                </Tooltip>
              ]}
            >
              <Card.Meta
                avatar={<Avatar icon={<UndoOutlined />} />}
                title={`订单: ${item.relatedOrder || '-'}`}
                description={
                  <div>
                    <p>期次: {item.paymentFrequency || '-'}</p>
                    <p>计划: {item.paymentPlan || '-'}</p>
                    <p>金额: {item.paymentAmount ? `$${parseFloat(item.paymentAmount).toFixed(2)}` : '-'}</p>
                    <p>日期: {item.countryDate ? new Date(item.countryDate).toLocaleDateString() : '-'}</p>
                    <p>负责人: {item.responsiblePerson || '-'}</p>
                    <div style={{ marginTop: 8 }}>
                      <Tag color={item.overdueStatus === '已逾期' ? 'red' : 'green'}>
                        {item.overdueStatus || 'Unknown'}
                      </Tag>
                      <Tag color={getStatusColor(item.approvalStatus)} style={{ marginLeft: 4 }}>
                        {getStatusText(item.approvalStatus)}
                      </Tag>
                    </div>
                  </div>
                }
              />
            </Card>
          </List.Item>
        )}
      />
    );
  };

  // 获取状态颜色
  const getStatusColor = (status) => {
    const colorMap = {
      '已通过': 'green',
      '待审批': 'blue',
      '被否决': 'red',
      '被驳回': 'orange',
      '已撤销': 'gray'
    };
    return colorMap[status] || 'default';
  };

  // 获取状态文本
  const getStatusText = (status) => {
    const textMap = {
      '已通过': '已通过',
      '待审批': '待审批',
      '被否决': '被否决',
      '被驳回': '被驳回',
      '已撤销': '已撤销'
    };
    return textMap[status] || status || '未知状态';
  };

  // 切换视图模式
  const toggleViewMode = () => {
    setViewMode(viewMode === 'table' ? 'card' : 'table');
  };

  // 表格列定义
  const columns = [

     {
           title: (
             <Checkbox
               checked={selectAll}
               onChange={handleSelectAll}
             />
           ),
           key: 'selection',
           width: 50,
           align: 'center',
           render: (_, record) => (
             <Checkbox
               checked={selectedRowKeys.includes(record.id)}
               onChange={() => onSelectChange(record.id)}
             />
           )
         },
    {
      title: (<span onClick={() => requestSort('systemNumber')}>系统编号 {getSortIcon('systemNumber')}</span>),
      dataIndex: 'systemNumber',
      key: 'systemNumber',
      align: 'center'
    },
    {
      title: (<span onClick={() => requestSort('relatedOrder')}>关联订单 {getSortIcon('relatedOrder')}</span>),
      dataIndex: 'relatedOrder',
      key: 'relatedOrder',
      align: 'center'
    },
    {
      title: (<span onClick={() => requestSort('countryDate')}>回款日期 {getSortIcon('countryDate')}</span>),
      dataIndex: 'countryDate',
      key: 'countryDate',
      align: 'center',
      render: (date) => date ? new Date(date).toLocaleDateString() : '-'
    },
    {
      title: (<span onClick={() => requestSort('paymentFrequency')}>回款期次 {getSortIcon('paymentFrequency')}</span>),
      dataIndex: 'paymentFrequency',
      key: 'paymentFrequency',
      align: 'center'
    },
    {
      title: (<span onClick={() => requestSort('paymentPlan')}>回款计划 {getSortIcon('paymentPlan')}</span>),
      dataIndex: 'paymentPlan',
      key: 'paymentPlan',
      align: 'center'
    },
    {
      title: (<span onClick={() => requestSort('paymentAmount')}>回款金额 {getSortIcon('paymentAmount')}</span>),
      dataIndex: 'paymentAmount',
      key: 'paymentAmount',
      align: 'center',
      render: (amount) => amount ? `$${parseFloat(amount).toFixed(2)}` : '-'
    },
    {
      title: (<span onClick={() => requestSort('overdueStatus')}>逾期状态 {getSortIcon('overdueStatus')}</span>),
      dataIndex: 'overdueStatus',
      key: 'overdueStatus',
      align: 'center',
      render: (status) => (
        <Tag color={status === '已逾期' ? 'red' : 'green'}>
          {status || 'Unknown'}
        </Tag>
      )
    },
    {
      title: (<span onClick={() => requestSort('approvalStatus')}>审批状态 {getSortIcon('approvalStatus')}</span>),
      dataIndex: 'approvalStatus',
      key: 'approvalStatus',
      align: 'center',
      render: (status) => {
        const statusMap = {
          '已通过': { color: 'green', text: '已通过' },
          '待审批': { color: 'blue', text: '待审批' },
          '被否决': { color: 'red', text: '被否决' },
          '被驳回': { color: 'orange', text: '被驳回' },
          '已撤销': { color: 'gray', text: '已撤销' }
        };
        const statusInfo = statusMap[status] || { color: 'default', text: status || 'Unknown' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      fixed: 'right',
      width: 220,
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="详情">
            <Button icon={<EyeOutlined />}>
              <Link to={`fundDetails/${record.id}`}>详情</Link>
            </Button>
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除此回款记录吗?"
              onConfirm={() => deleteFundsrecoverymanagement(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="danger" icon={<DeleteOutlined />}>删除</Button>
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  return (
    <div className="funds-recovery-management">
      <Card bordered={false}>
        {/* 顶部标签页 */}
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="全部回款" key="all" />
{/*           <TabPane tab="我的回款" key="mine" /> */}
{/*           <TabPane tab="下属回款" key="next" /> */}
        </Tabs>

        {/* 筛选表单 */}
        <Form form={form} name="search-form" onFinish={handleSearch} layout="vertical" className="search-form">
          <div className="search-fields" style={{display: 'flex', flexWrap: 'wrap', gap: '16px'}}>
            <Form.Item name="keyword" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Input placeholder="系统编号/订单号" allowClear prefix={<SearchOutlined />}/>
            </Form.Item>
            <Form.Item name="approvalstatus" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Select placeholder="审批状态" allowClear>
                <Option value="all">全部状态</Option>
                <Option value="待审批">待审批</Option>
                <Option value="已通过">已通过</Option>
                <Option value="被否决">被否决</Option>
                <Option value="被驳回">被驳回</Option>
                <Option value="已撤销">已撤销</Option>
              </Select>
            </Form.Item>
            <Form.Item name="overduestatus" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Select placeholder="逾期状态" allowClear>
                <Option value="all">全部状态</Option>
                <Option value="未逾期">未逾期</Option>
                <Option value="已逾期">已逾期</Option>
              </Select>
            </Form.Item>
            <Form.Item name="paymentmethod" className="search-field" style={{flex: 1, minWidth: '200px'}}>
              <Select placeholder="付款方式" allowClear>
                <Option value="all">全部方式</Option>
                <Option value="银行转账">银行转账</Option>
                <Option value="支付宝">支付宝</Option>
                <Option value="微信支付">微信支付</Option>
                <Option value="现金">现金</Option>
                <Option value="支票">支票</Option>
                <Option value="信用证">信用证</Option>
              </Select>
            </Form.Item>
            <Form.Item name="dateRange" className="search-field" style={{flex: 1, minWidth: '250px'}}>
              <RangePicker style={{ width: '100%' }} allowClear />
            </Form.Item>
            <div className="form-actions">
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
              <Button onClick={onReset} icon={<ReloadOutlined />} style={{ marginLeft: 8 }}>重置</Button>
            </div>
          </div>
        </Form>

        <Divider />

          {/* 操作按钮 */}
          <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/addfundsrecovery')}>
                        添加回款记录
          </Button>
          <Button icon={<ImportOutlined />} onClick={showImportModal}>导入</Button>
          <Button icon={<ExportOutlined />} onClick={handleExport} loading={exportLoading}>导出</Button>

          {/* 添加反选按钮 */}
          <Button icon={<UndoOutlined />} onClick={handleInvertSelection}>
          反选
          </Button>

          {/* 批量删除按钮 */}
          <Button
            type="danger"
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            批量删除
          </Button>

          {/* 显示已选择数量 */}
          {selectedRowKeys.length > 0 && (
          <span style={{ marginLeft: 8, color: '#1890ff' }}>
          已选择 {selectedRowKeys.length} 项
          </span>
          )}
          </Space>
          <Space>
          <Dropdown overlay={sortMenu} trigger={['click']}>
          <Button icon={<SortAscendingOutlined />}>排序</Button>
          </Dropdown>
          <Button
            icon={viewMode === 'table' ? <AppstoreOutlined /> : <TableOutlined />}
            onClick={toggleViewMode}>
            {viewMode === 'table' ? '卡片视图' : '表格视图'}
            </Button>
            </Space>
            </div>


        {/* 根据视图模式显示不同内容 */}
        {viewMode === 'table' ? (
          <Table
            columns={columns}
            dataSource={filteredData}
            loading={loading}
            bordered
            rowKey="id"
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
        ) : (
          renderCardView()
        )}

        {/* 导入弹窗 */}
        <Modal
          title="导入回款数据"
          visible={importModalVisible}
          onCancel={hideImportModal}
          footer={[
            <Button key="cancel" onClick={hideImportModal}>取消</Button>,
            <Button
              key="import"
              type="primary"
              loading={importLoading}
              onClick={handleImport}
              icon={<ImportOutlined />}
            >
              开始导入
            </Button>
          ]}
        >
          <Upload
            multiple
            fileList={fileList}
            onChange={handleUploadChange}
            beforeUpload={() => false} // 阻止自动上传
            accept=".xlsx,.xls,.csv"
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
          <div style={{ marginTop: 16 }}>
            <p>支持格式: .xlsx, .xls, .csv</p>
            <p>文件大小限制: 10MB</p>
            <p>请确保文件格式与模板一致</p>
          </div>
        </Modal>
      </Card>
    </div>
  );
}